package com.shine.log.listener;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.shine.log.entity.RequestLog;
import com.shine.rabbitmq.request.CommonLogRequest;
import com.shine.log.service.RequestLogService;
import com.shine.rabbitmq.constant.RabbitConstant;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author huihui
 * @date 2025/5/7 14:21
 * @description RequestLogListener
 */
@Slf4j
@Service
public class RequestLogListener {

    @Resource
    private RequestLogService requestLogService;

    @RabbitListener(queues = RabbitConstant.Gateway.COMMON_LOG_QUEUE, batch = "3-5")
    public void requestLogCustomerMessage(Message message, Channel channel) throws Exception {
        String body = new String(message.getBody());
        log.warn("接收到消息：{}", body);
        // 签收消息
        try {
            CommonLogRequest commonLogRequest = JSON.parseObject(body, CommonLogRequest.class);
            RequestLog requestLog = this.buildEntity(commonLogRequest);
            requestLogService.save(requestLog);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.warn("消息签收成功！");
        } catch (IOException e) {
            log.error("消息签收失败", e);
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, true);
                log.warn("拒绝签收成功！");
            } catch (IOException ex) {
                log.error("拒绝签收失败！", ex);
            }
        } catch (Exception e) {
            log.error("消息签收出错：", e);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    private RequestLog buildEntity(CommonLogRequest request) {
        RequestLog entity = new RequestLog();
        entity.setTraceId(request.getTraceId());
        entity.setIp(request.getIp());
        entity.setUri(request.getUri());
        entity.setPath(request.getPath());
        entity.setRequestTime(request.getRequestTime());
        entity.setRequestMethod(request.getRequestMethod());
        entity.setRequestHeaders(request.getRequestHeaders());
        entity.setRequestParams(request.getRequestParams());
        entity.setClientId(request.getClientId());
        entity.setUserId(request.getUserId());
        entity.setUsername(request.getUsername());
        entity.setService(request.getService());
        return entity;
    }

}
